package com.monlyu.action.sql;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import com.monlyu.action.system.DownloadAction;
import com.monlyu.bean.Pages;
import com.monlyu.bo.SqlBo;

/**
 * @since Zengjun 2009-3-18
 */
public class SqlDownloadAction extends DownloadAction {

	protected String defaultSorted() {
		return "-id";
	}

	private String sql;

	private SqlBo sqlBo;
	private static List eroroSql = new ArrayList(100);

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String execute() {
		return SUCCESS;
	}

	private static void rememberError(String sql) {
		if (eroroSql.size() > 99) {
			eroroSql.remove(99);
		}
		eroroSql.add(sql);
	}

	public String toExport() throws Exception {
		try {
			filename ="sqlResult.xls";
			if (isErrorSql(sql)) {
				inputStream = new ByteArrayInputStream(new byte[0]);
			} else {
				inputStream = sqlBo.getExportInputStream(sql.replaceAll(";",
						""));
			}
		} catch (RuntimeException e) {
			throw e;
		}
		return download("xls");
	}

	private static boolean isErrorSql(String sql) {
		return eroroSql.contains(sql);
	}

	public String getSql() {
		return sql;
	}

	public void setSqlBo(SqlBo sqlBo) {
		this.sqlBo = sqlBo;
	}
}
